package com.zrb.mobile;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
 
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
 
import com.zrb.mobile.adapter.GdpListAdapter;
import com.zrb.mobile.adapter.model.GdpInfos;
import com.zrb.mobile.adapter.model.ProjectCityDto;
import com.zrb.mobile.adapter.model.ProjectCityDtos;
import com.zrb.mobile.adapter.model.inspectStatisticDto;
import com.zrb.mobile.fadingactionbar.SherlockFadingActionBarHelper;
import com.zrb.mobile.ui.ObserveScrollView;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.DialogBuilder;
import com.zrb.mobile.utility.ZrbRestClient;

import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.Chart;
import lecho.lib.hellocharts.view.PieChartView;

public class Project_cityInfoActivity extends SherlockFragmentActivity implements OnClickListener {

	RelativeLayout mtitleLayout;
	ObserveScrollView mscrollview;
	private Fragment currentFragment = null;
	ViewPager mViewPager;
	int curId;
	RadioButton gdptotalBtn,gdpRateBtn;
	View customNav;
	
	
	TextView cityGdpvalue,mcitypeopleNum,mcitypeopleIncome,mcitytown;
	
	TextView cityname,cityIntroduce;
	TextView mfirstpercent,msecondpercent,mthirdpercent;
	LinearLayout city_tagcontainer;
	private ProjectCityDto mprojectCityDto;
	PlaceholderFragment chartFragment;
	int postCode=-1;
	private Handler handler = new Handler();
	
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        
        SherlockFadingActionBarHelper helper = new SherlockFadingActionBarHelper()
        .actionBarBackground(R.drawable.app_bg3)
        .headerLayout(R.layout.project_city_head)
        .contentLayout(R.layout.project_city_content);;
        
        setContentView(helper.createView(this));
        helper.initActionBar(this); 
  
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        
        if (bundle != null)
    		restoreSelf(bundle);
    	else 
    		postCode=this.getIntent().getIntExtra("postCode", -1);
        
        //Inflate the custom view
         customNav = LayoutInflater.from(this).inflate(R.layout.project_fadingbar, null);
         getSupportActionBar().setCustomView(customNav);
         getSupportActionBar().setDisplayShowCustomEnabled(true);
         initView();
         initViewpager();
         loadData();
    }
    
    @Override
	protected  void onSaveInstanceState(Bundle outState) {
       super.onSaveInstanceState(outState);
       outState.putInt("postCode", postCode);
    }

     private void restoreSelf(Bundle savedInstanceState){
    	 postCode = savedInstanceState.getInt("postCode",-1);
    }
    
    private void loadData(){
    	
    	//http://172.17.32.253:8090/projectApi/getCityInfo?postCode=421182
        	String url=String.format("projectApi/getCityInfo?postCode=%1$s", postCode);
    		ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler()
        	{
      			@Override
    			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
        			handerError(Project_cityInfoActivity.this.getString(R.string.error_net_loadfail));
    			}

    			@Override
    			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
     				String results=new String(arg2);
    				try {
    			        Gson gson =new Gson();  
    			        ProjectCityDtos tmpDto=	gson.fromJson(results, ProjectCityDtos.class);
    			         if(tmpDto.res==1){
    			        	 cityname.setText(tmpDto.data.province+"."+tmpDto.data.city) ;
    			        	 mprojectCityDto=tmpDto.data;
    			        	 initViewpager(); 
						     chartFragment.refleshDataAnimation(
								        mprojectCityDto.primaryIndustry,
								        mprojectCityDto.secondIndustry,
								        mprojectCityDto.tertiaryIndustry);  
    			        	 float total=mprojectCityDto.primaryIndustry+mprojectCityDto.secondIndustry+mprojectCityDto.tertiaryIndustry;
						     mfirstpercent.setText((int)(100*mprojectCityDto.primaryIndustry/total)+"%");
						     msecondpercent.setText((int)(100*mprojectCityDto.secondIndustry/total)+"%");
						     mthirdpercent.setText((int)(100*mprojectCityDto.tertiaryIndustry/total)+"%");
						    
    			        	 if(!TextUtils.isEmpty(tmpDto.data.keyWords)){
     			        		 String[] tmpArr=tmpDto.data.keyWords.split("#");
     			        		 for(int i=0;i<city_tagcontainer.getChildCount();i++){
     			        			 if(i<tmpArr.length)
     			        				 ((TextView)city_tagcontainer.getChildAt(i)).setText(tmpArr[i]) ;
     			        			 else
     			        				city_tagcontainer.getChildAt(i).setVisibility(View.GONE);
     			        		 }
   			        	     }
    			        	 cityIntroduce.setText(tmpDto.data.intro) ;
    			        	 showCityGdp();
    			        }
    			        else{
    			        	handerError(tmpDto.msg);
    			        } 
        			}
    				catch(Exception e){
    					handerError(Project_cityInfoActivity.this.getString(R.string.error_serverdata_loadfail));
      				}
    			}});
     }
    
    private void handerError(String msg){
        handler.removeCallbacks(run);
   	    cityGdpvalue.setText("--");
   	    cityIntroduce.setText(msg) ;
   	    CommonUtil.showToast(msg, Project_cityInfoActivity.this);
    }
    
    private void showCityGdp(){
    
   	    handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					 handler.removeCallbacks(run);
					 cityGdpvalue.setText(mprojectCityDto.gdp==0 ? "--":String.valueOf(mprojectCityDto.gdp));
 					      
				    if(mprojectCityDto.population>0)
							mcitypeopleNum.setText(Project_cityInfoActivity.this.getString(
								     	  R.string.city_people_num).replace("--", mprojectCityDto.population + ""));
				    if(mprojectCityDto.pcdi>0)
				    		mcitypeopleIncome.setText(Project_cityInfoActivity.this.getString(
							     	  R.string.city_people_income_peryear).replace("--", mprojectCityDto.pcdi + ""));
				    	 
				    if(mprojectCityDto.urbanRate>0)
				    		mcitytown.setText(Project_cityInfoActivity.this.getString(
							     	  R.string.city_town_percent).replace("--", mprojectCityDto.urbanRate + ""));
				}
      	 }, 500);
    }
    
	private void initView(){
		
 	    cityname=(TextView)this.findViewById(R.id.city_name_txt);
 	    cityIntroduce=(TextView)this.findViewById(R.id.city_des);
 	    
 	    cityGdpvalue=(TextView)this.findViewById(R.id.city_gdp_count);
 	    
 		mcitypeopleNum=(TextView)this.findViewById(R.id.citypeople_num);
	    mcitypeopleIncome=(TextView)this.findViewById(R.id.citypeople_income);
	    mcitytown=(TextView)this.findViewById(R.id.citytown_percent);
 	    
 	    mfirstpercent=(TextView)this.findViewById(R.id.firstpercent);
 	    msecondpercent=(TextView)this.findViewById(R.id.secondpercent);
 	    mthirdpercent=(TextView)this.findViewById(R.id.thirdpercent);
  	   
 	    city_tagcontainer=(LinearLayout) this.findViewById(R.id.city_tagcontainer);
  		
 	 	View lefticon= customNav.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this); 
	//	TextView txtTitle=	(TextView)this.findViewById(R.id.txt_title);
		this.findViewById(R.id.re_industry_distribution).setOnClickListener(this);;
 	 
		// mscrollview.setOnTouchListener(scrollTouch);
 	 	this.findViewById(R.id.img_gdpmore).setOnClickListener(this);;
  
  		mViewPager = (ViewPager) findViewById(R.id.gdp_chat_viewpager);
		mViewPager.setOffscreenPageLimit(3);
		
		//gdptotalBtn,gdpRateBtn
		gdptotalBtn=(RadioButton)this.findViewById(R.id.mymsg_chk0);
		gdpRateBtn=(RadioButton)this.findViewById(R.id.sysmsg_chk1);
		gdptotalBtn.setOnClickListener(this);
		gdpRateBtn.setOnClickListener(this);
		curId=R.id.mymsg_chk0;
		
		chartFragment= new PlaceholderFragment();
		getSupportFragmentManager().beginTransaction().add(R.id.chart_content_frame, chartFragment).commit();
		startTimer();
   	}
    
	 private void startTimer() {
	        handler.removeCallbacks(run);
	        handler.postDelayed(run, 50);
	}
	
	  private Runnable run = new Runnable() {

	        @Override
	        public void run() {
	            String str;
	            if (cityGdpvalue.getText().toString().indexOf(",") >= 0) {
	                str = cityGdpvalue.getText().toString().replace(",", "");
	            } else {
	                str = cityGdpvalue.getText().toString();
	            }
	            double s = Double.parseDouble(str);
	            double trueS = 2232018.21;
	            double i = 0;
	            if (trueS > 99999) {
	                i = s + 12131.12;
	            } else if (trueS > 9999) {
	                i = s + 1213.21;
	            } else if (trueS > 999) {
	                i = s + 102.12;
	            } else if (trueS > 99) {
	                i = s + 11.21;
	            } else {
	                i = s + 1.11;
	            }

	            if (i < (trueS - trueS / 10)) {

	                double d = Double.parseDouble(String.format("%.2f", i));

	                String strI = String.valueOf(d);

	                if (strI.length() <= 6) {
	                	cityGdpvalue.setText(strI);
	                } else if (strI.length() > 6 && strI.length() <= 9) {
	                	cityGdpvalue.setText(strI.substring(0, strI.length() - 6) + ","
	                            + strI.substring(strI.length() - 6));
	                } else {
	                	cityGdpvalue.setText(strI.substring(0, strI.length() - 9)
	                            + ","
	                            + strI.substring(strI.length() - 9,
	                                    strI.length() - 6) + ","
	                            + strI.substring(strI.length() - 6));
	                }

	            } else {

	                String stt = "2232018.21";

	                if (stt.length() <= 6) {
	                	cityGdpvalue.setText(stt);
	                } else if (stt.length() > 6 && stt.length() <= 9) {
	                	cityGdpvalue.setText(stt.substring(0, stt.length() - 6) + ","
	                            + stt.substring(stt.length() - 6));
	                } else {
	                	cityGdpvalue.setText(stt.substring(0, stt.length() - 9) + ","
	                            + stt.substring(stt.length() - 9, stt.length() - 6)
	                            + "," + stt.substring(stt.length() - 6));
	                }

	            }

	            if (i < trueS) {
	                handler.postDelayed(run, 50);
	            }

	        }
	    };
	
	
	private void initViewpager() {
 		FragmentPagerAdapter mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
 			@Override
			public int getCount() { return 2; }

			@Override
			public Fragment getItem(int position) {
 				return  getCurrentFragment(position);
   			}
 	   };
 	  mViewPager.setAdapter(mAdapter);
	  mViewPager.setCurrentItem(0);
	  mViewPager.setOnPageChangeListener(new OnPageChangeListener(){
			@Override
			public void onPageSelected(int position){
				if (position == 0){
					  curId=R.id.mymsg_chk0;
					  gdptotalBtn.setChecked(true);
				   }
		          if (position == 1) { 
		        	  curId=R.id.sysmsg_chk1;
		        	  gdpRateBtn.setChecked(true);
		           };
			}

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				 
			}

			@Override
			public void onPageScrollStateChanged(int state){}
		 
		});
 	}
	
	private Fragment getCurrentFragment(int postion){
		//return null;
		 
		 List<inspectStatisticDto> inspectStatistics=new ArrayList<inspectStatisticDto>();
 		/* for(int i=0;i<mprojectCityDto.cityStatistics.size();i++){
				 
			 float curValue=postion==0 ?  mprojectCityDto.cityStatistics.get(i).gdp:mprojectCityDto.cityStatistics.get(i).gdpRate;
			 String curName=mprojectCityDto.cityStatistics.get(i).date;
			 inspectStatisticDto tmp =new inspectStatisticDto(curName,curValue);
			 inspectStatistics.add(tmp);
		 }*/
		 for(int i=0;i<7;i++){
		   // LinePoint tmp=new LinePoint(getActivity(), i, (int) (Math.random() * (maxY - minY) + minY));
		    
		    inspectStatisticDto tmp =new inspectStatisticDto(2010+"", (int) (Math.random() * (6 - 1) + 1));
		    inspectStatistics.add(tmp);
		 }
  		return MarkedPointsChartFragment.newInstance("MarkedPoint",inspectStatistics,postion,postion==0? false:true); 
	}
   
    /**
     * A fragment containing a pie chart.
     */
    public static class PlaceholderFragment extends Fragment {

        private PieChartView chart;
        private PieChartData data;

        private boolean hasLabels = false;
        private boolean hasLabelsOutside = false;
        private boolean hasCenterCircle = true;
        private boolean hasCenterText1 = false;
        private boolean hasCenterText2 = false;
        private boolean isExploded = false;
        private boolean hasLabelForSelected = false;

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           
            View rootView = inflater.inflate(R.layout.fragment_pie_chart, container, false);

            chart = (PieChartView) rootView.findViewById(R.id.chart);
            chart.setOnValueTouchListener(new ValueTouchListener());

            generateData();
            return rootView;
        }
  
        private void reset() {
            chart.setCircleFillRatio(1.0f);
            hasLabels = false;
            hasLabelsOutside = false;
            hasCenterCircle = false;
            hasCenterText1 = false;
            hasCenterText2 = false;
            isExploded = false;
            hasLabelForSelected = false;
        }

        private void generateData() {
            int numValues = 3;

            int[] colors={Color.parseColor("#59e387"),Color.parseColor("#fabb7d"),Color.parseColor("#2e96ff")};
            
            List<SliceValue> values = new ArrayList<SliceValue>();
            for (int i = 0; i < numValues; ++i) {
                SliceValue sliceValue = new SliceValue((float) Math.random() * 30 + 15,colors[i]);// ChartUtils.pickColor()
                values.add(sliceValue);
            }

            data = new PieChartData(values);
            data.setHasLabels(hasLabels);
            data.setHasLabelsOnlyForSelected(hasLabelForSelected);
            data.setHasLabelsOutside(hasLabelsOutside);
            data.setHasCenterCircle(hasCenterCircle);

            if (isExploded) {
                data.setSlicesSpacing(24);
            }

            if (hasCenterText1) {
                data.setCenterText1("Hello!");
                 data.setCenterText1FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
                        (int) getResources().getDimension(R.dimen.pie_chart_text1_size)));
            }

            if (hasCenterText2) {
                data.setCenterText2("Charts (Roboto Italic)");
                data.setCenterText2FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
                        (int) getResources().getDimension(R.dimen.pie_chart_text2_size)));
            }
            chart.setPieChartData(data);
        }
 
        /**
         * To animate values you have to change targets values and then call {@link Chart#startDataAnimation()}
         * method(don't confuse with View.animate()).
         */
        private void prepareDataAnimation() {
            for (SliceValue value : data.getValues()) {
                value.setTarget((float) Math.random() * 30 + 15);
            }
        }

        public void refleshDataAnimation(float first,float second,float third){
         
        	   data.getValues().get(0).setTarget(first);
        	   data.getValues().get(1).setTarget(second);
        	   data.getValues().get(2).setTarget(third);
        	   chart.startDataAnimation();
        }
        
        private class ValueTouchListener implements PieChartOnValueSelectListener {

            @Override
            public void onValueSelected(int arcIndex, SliceValue value) {
               // Toast.makeText(getActivity(), "Selected: " + value, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onValueDeselected() {
                // TODO Auto-generated method stub

            }

        }
    }

    
	private Dialog tmpdialSetting;
	private ListView tmpsetlistView;
	//private View loadview;
	private void Setting(){
		 
	    if(tmpdialSetting!=null){
	    	tmpdialSetting.show();
	    	return;
	    }	
		DialogBuilder tmpbuild = new DialogBuilder(this);
		tmpbuild.setContentView(R.layout.project_city_gdpdialog);
 		View rootview = tmpbuild.getCurContentView();
 		//loadview=rootview.findViewById(R.id.listgpd_loading);
 	/*	cancelBtn =rootview.findViewById(R.id.cancel_btn);
 		cancelBtn.setOnClickListener(this);*/
  			
 		rootview.findViewById(R.id.cancel_imgbtn).setOnClickListener(this);
 		
 		tmpsetlistView = (ListView) rootview.findViewById(R.id.listView1);
  		tmpdialSetting = tmpbuild.createDialog(this, R.style.scaleInDialog,false); //bottomInDialog
  		
  		handler.postDelayed(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String url=String.format("projectApi/getCityEconomic?postCode=%1$s", postCode);
				ZrbRestClient.get(url, null,  new AsyncHttpResponseHandler(){
		  			@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
		   			   CommonUtil.showToast(Project_cityInfoActivity.this.getString(R.string.error_net_loadfail), Project_cityInfoActivity.this);	
					}

					@Override
					public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
		 				String results=new String(arg2);
						try {
					        Gson gson =new Gson();  
					        GdpInfos tmpDto=	gson.fromJson(results, GdpInfos.class);
					        if(tmpDto.res==1){
					       // 	loadview.setVisibility(View.GONE);
		 			      		GdpListAdapter tmpAdapter=new GdpListAdapter(Project_cityInfoActivity.this,tmpDto.data);
		 			    		tmpsetlistView.setAdapter(tmpAdapter);
					        }
					        else{
					        	 CommonUtil.showToast(tmpDto.msg, Project_cityInfoActivity.this);	
					        } 
		    			}
						catch(Exception e){
		 				   //loadingview.HideText(e.getMessage()).ShowRefleshBtn(true).ShowError();
							 CommonUtil.showToast(Project_cityInfoActivity.this.getString(R.string.error_serverdata_loadfail), Project_cityInfoActivity.this);	
		 				}
		 		}});
			}}, 250);
		
     }
    
    
    @Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.cancel_imgbtn:
			if(tmpdialSetting!=null) tmpdialSetting.dismiss();
			break;
    	case R.id.img_gdpmore:
    		 Setting();
      		break;
       case R.id.mymsg_chk0:
		   mViewPager.setCurrentItem(0,true);
           break;
	   case R.id.sysmsg_chk1:
		   mViewPager.setCurrentItem(1,true);
           break;
	   case R.id.re_industry_distribution:
			Intent it = new Intent(this, Project_popup_industry.class);
		     it.putExtra("postCode", postCode);
			 startActivity(it);  
		   
		   break;
     	 
 		}
 	}
}
